package com.hmdp.core.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.common.constant.SystemConstants;
import com.hmdp.core.service.IShopService;
import com.hmdp.entity.db.Shop;
import com.hmdp.core.mapper.ShopMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.entity.dto.Result;
import com.hmdp.common.constant.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    public RedisServiceImpl redisService;
    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    /**
     * 初始化店铺信息
     */
    @PostConstruct
    public void initShop() {
        log.info("缓存店铺经纬度信息start");
        List<Shop> shops = this.list(new LambdaQueryWrapper<>(null));
        Map<Long, List<Shop>> typeMap = shops.stream().collect(Collectors.groupingBy(Shop::getTypeId));
        typeMap.forEach((k,v) -> {
            String key = RedisConstants.SHOP_GEO_KEY + k;
            stringRedisTemplate.delete(key);
            List<RedisGeoCommands.GeoLocation<String>> locations = v.stream()
                    .map(m -> new RedisGeoCommands.GeoLocation<String>(
                            m.getId().toString(),
                            new Point(m.getX(), m.getY()
                            ))
                    ).collect(Collectors.toList());
            stringRedisTemplate.opsForGeo().add(key,locations);
        });
        log.info("缓存店铺经纬度信息end");
    }

    @Override
    public Result one(Long id) {
        //缓存穿透
//        Shop shop = redisService.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY,id,Shop.class,this::getById,
//                RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);

        //互斥锁解决缓存击穿
        Shop shop = redisService.queryWithMutex(RedisConstants.CACHE_SHOP_KEY,id,Shop.class,this::getById);

        //逻辑过期解决缓存击穿
//        Shop shop = redisService.queryWithLogicExpire(RedisConstants.CACHE_SHOP_KEY,id,Shop.class,this::getById, 20L,TimeUnit.SECONDS);

        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    @Override
    @Transactional
    public Result updateOne(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("id为空");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        redisService.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        if(x == null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = this.query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 1. 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 2. 查询
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );

        // 3. 解析
        if(results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size() < from) {
            // 无数据
            return Result.ok(Collections.emptyList());
        }

        // 4. 截取
        List<Long> ids = new ArrayList<>(list.size());
        Map<String,Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(f -> {
            // 获取店铺id
            String shopIdStr = f.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 获取距离
            Distance distance = f.getDistance();
            distanceMap.put(shopIdStr,distance);
        });

        // 5. 查询店铺信息
        if(ids.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        String idStr = StrUtil.join(",", ids);
        List<Shop> shopList = lambdaQuery().in(Shop::getId, ids).last("order by field(id," + idStr + ")").list();

        // 6. 插入距离信息
        shopList.forEach(f -> f.setDistance(distanceMap.get(f.getId().toString()).getValue()));

        return Result.ok(shopList);
    }
}
